<template>
  <div class="nav-rights">
    <div class="nav-right col-xs-12 col-md-10 padding-right-clear">
      <div class="bill_box rightarea padding-right-clear">
        <div class="shaow">
          <div class="money_table">
            <div style="width: 100%;height: 70px;">
            <div style="float:left;letter-spacing:1px;padding-top: 5px;">
              <div style="padding-top: 5px;">
                <span style="font-size:12px;color:#828ea1;">{{$t('uc.finance.money.balance')}}：{{balanceWallet.balance ? balanceWallet.balance : 0}}</span>
                <span style="font-size:12px;color:#828ea1;">{{$t('uc.finance.money.frozenbalance')}}：{{balanceWallet.frozenBalance ? balanceWallet.frozenBalance : 0}}</span>
                <span style="font-size:12px;color:#828ea1;">{{$t('uc.finance.money.needreleasedbalance')}}：{{balanceWallet.toReleased ? balanceWallet.toReleased : 0}}</span>
                <span style="font-size:12px;color:#828ea1;">{{$t('uc.finance.money.storagefee')}}：{{ balanceWallet.storageFee ? balanceWallet.storageFee : 0 }}</span>
            </div>
            </div>
            <Input style="float:right;" class="search" search :placeholder="$t('common.searchplaceholder')" @on-change="seachInputChange" v-model="searchKey"/>
            </div>
            <!-- tableMoneyShow -->
            <Table :columns="tableColumnsMoney" :data="tableMoneyShow" :loading="loading" :disabled-hover="true"></Table>
          </div>
        </div>
      </div>
    </div>
    <!-- 提币Modal -->
    <!-- :rules="ruleValidate"  -->
    <Modal v-model="modal" title="提取" @on-ok="handleSubmit('withdrawForm')" @on-cancel="handleReset('withdrawForm')">
      <Form ref="withdrawForm" :rules="ruleValidate" :model="withdrawForm" :label-width="85">
        <FormItem label="型号">
          <span>{{ rowVal.symbol }}</span>
        </FormItem>
        <FormItem label="可用数量">
          <span>{{ toFloor((Number(rowVal.toReleased || 0) + Number(rowVal.amount || 0)), 0) }}</span>
        </FormItem>
        <!-- amount -->
        <FormItem label="提币数量" prop="amount">
          <Input v-model="withdrawForm.amount" number size="large"></Input>
        </FormItem>
        <!-- address -->
        <FormItem label="地址">
          <span>{{ user.address }}</span>
        </FormItem>
        <!-- code -->
        <FormItem label="验证码" prop="code">
          <Input type="text" v-model="withdrawForm.code" :placeholder="$t('uc.regist.smscode')">
          </Input>
          <input class="form-code" id="sendCode" @click="sendCode();" shape="circle" type="Button" :value="sendcodeValue" :disabled="codeIsSending">
          </input>
        </FormItem>
        <!-- passwd -->
        <FormItem label="资金密码" prop="password">
          <Input v-model="withdrawForm.password" type="password" size="large"></Input>
        </FormItem>
        <FormItem label="备注">
          <Input v-model="withdrawForm.remark" type="text" size="large"></Input>
        </FormItem>
      </Form>
    </Modal>
  </div>
</template>
<script>
export default {
  components: {},
  data() {
    const validateAmount = (rule, value, callback) =>  {
      if(value === "" || Number(value) === 0) {
        callback(new Error("请输入提取数量"));
      } else if((parseInt(value)%this.rowVal.coin.unit) === 0) {
        if(Number(this.rowVal.toReleased || 0) + Number(this.rowVal.amount || 0) < Number(value)) {
          callback(new Error('提取数量不能大于可提数量'));
        } else {
          callback();
        }
      } else {
        callback(new Error("请输入正确的数量"));
      }
    };
    const validateCode = (rule, value, callback) =>  {
      if(value === "") {
        callback(new Error("请输入短信验证码"));
      } else {
        callback();
      }
    };
    const validatePassword = (rule, value, callback) =>  {
      if(value === "") {
        callback(new Error("请输入资金密码"));
      } else {
        callback();
      }
    };
    return {
      modal: false,
      loginmsg: this.$t("common.logintip"),
      loading: true,
      balanceWallet: {},
      tableMoney: [],
      tableMoneyShow: [],
      searchKey: "",
      user: {
        memberLevel: 1
      },

      rowVal: {},
      withdrawForm: {
        amount: '',
        code: '',
        password: '',
        remark: ''
      },
      codeIsSending: false,
      sendcodeValue: this.$t("uc.regist.sendcode"),
      countdown: 60,
      ruleValidate: {
        amount: [{ required: true, type: 'number', validator: validateAmount, trigger: 'blur' }],
        code: [{ required: true, validator: validateCode, trigger: 'blur' }],
        password: [{ required: true, validator: validatePassword, trigger: 'blur' }]
      },
    };
  },
  computed: {

  },
  methods: {
    handleReset(name) {
      this.$refs[name].resetFields();
    },
    handleSubmit(name) {
      this.$refs[name].validate(valid => {
        if(valid) {
          var params = {};
          params["symbol"] = this.rowVal.symbol;
          params["amount"] = this.withdrawForm.amount;
          params["code"] = this.withdrawForm.code;
          params["jyPassword"] = this.withdrawForm.password;
          params["storageFee"] = this.rowVal.storageFee ? this.rowVal.storageFee : 0;
          params["remark"] = this.withdrawForm.remark;
          this.$http.post(this.host + '/api/uc/coin-wallet-withdraw/apply/code', params).then(response => {
            if (response.code == 0) {
              this.loading = false;
              this.modal = false;
              this.handleReset(name);
              this.$Message.success(response.message);
            } else {
              this.$Message.error(response.message);
            }
          });
        }
      });
    },
    seachInputChange(){
      this.tableMoneyShow = this.tableMoney.filter(item => item["symbol"].indexOf(this.searchKey) == 0);
    },
    getUserInfo() {
      this.$http.post(this.host + "/api/uc/member/my-info").then(response => {
        var resp = response.body;
        if(resp.code == 0) {
          this.user = resp.data;
        } else {
          this.$Message.error(this.loginmsg);
        }
      });
    },
    getMoney() {
      // 获取资金
      this.$http.post(this.host + "/api/uc/asset/balanceWallet").then(response => {
        var resp = response.body;
        if (resp.code == 0) {
          this.balanceWallet = resp.data;
          this.loading = false;
        } else {
          this.$Message.error(this.loginmsg);
        }
      });
      //获取资产
      this.$http.post(this.host + "/api/uc/asset/coinWallet").then(response => {
        var resp = response.body;
        if (resp.code == 0) {
          this.tableMoney = resp.data;
          for (let i = 0; i < this.tableMoney.length; i++) {
            this.tableMoney[i]["symbol"] = this.tableMoney[i].coin.symbol;
          }
          this.loading = false;
          this.tableMoneyShow = this.tableMoney;
        } else {
          this.$Message.error(this.loginmsg);
        }
      });
    },
    sendCode() {
      console.log("send withdraw code");
      this.$http.post(this.host + "/api/uc/mobile/withdraw/code").then(response => {
        var resp = response.body;
        if (resp.code == 0) {
          this.settime();
          this.$Notice.success({
            title: this.$t("common.tip"),
            desc: resp.message
          });
        } else {
          this.$Notice.error({
            title: this.$t("common.tip"),
            desc: resp.message
          });
        }
      });
    },
    settime() {
      this.sendcodeValue = "重新发送（" + this.countdown + "）";
      this.codeIsSending = true;
      let timercode = setInterval(() => {
        this.countdown--;
        this.sendcodeValue = "重新发送（" + this.countdown + "）";
        if (this.countdown <= 0) {
          clearInterval(timercode);
          this.sendcodeValue = this.$t("uc.regist.sendcode");
          this.countdown = 60;
          this.codeIsSending = false;
        }
      }, 1000);
    },
  },
  created() {
    this.getMoney();
    this.getUserInfo();
  },
  computed: {
    totalUSDT() {
      let usdtTotal = 0;
      for (let i = 0; i < this.tableMoney.length; i++) {
        usdtTotal +=  (this.tableMoney[i].balance + this.tableMoney[i].frozenBalance) * this.tableMoney[i].coin.usdRate;
      }
      return usdtTotal.toFixed(2);
    },
    totalCny(){
      let cnyTotal = 0;
      for (let i = 0; i < this.tableMoney.length; i++) {
        cnyTotal +=  (this.tableMoney[i].balance + this.tableMoney[i].frozenBalance) * this.tableMoney[i].coin.cnyRate;
      }
      return cnyTotal.toFixed(2);
    },
    tableColumnsMoney() {
      let self = this;
      let columns = [];
      columns.push({
        title: this.$t("uc.finance.money.symbol"),
        width: 180,
        align: "center",
        render(h, params) {
          return h(
            "span",
            params.row.coin.symbol
          );
        }
      });
      columns.push({
        title: this.$t("uc.finance.money.genre"),
        align: "center",
        render(h, params) {
          return h(
            "span",
            params.row.coin.genre
          );
        }
      });
      columns.push({
        title: this.$t("uc.finance.money.brand"),
        align: "center",
        render(h, params) {
          return h(
            "span",
            params.row.coin.brand
          );
        }
      });
      columns.push({
        title: this.$t("uc.finance.money.amount"),
        align: "center",
        render(h, params) {
          return h(
            "span",
            {
              attrs: {
                title: params.row.amount
              }
            },
            self.toFloor(params.row.amount || "0")
          );
        }
      });
      columns.push({
        title: this.$t("uc.finance.money.frozenamount"),
        align: "center",
        render(h, params) {
          return h(
            "span",
            {
              attrs: {
                title: params.row.frozenAmount
              }
            },
            self.toFloor(params.row.frozenAmount || "0")
          );
        }
      });
      columns.push({
        title: this.$t("uc.finance.money.needreleasedamount"),
        align: "center",
        render(h, params) {
          return h(
            "span",
            {
              attrs: {
                title: params.row.toReleased
              }
            },
            self.toFloor(params.row.toReleased || "0")
          );
        }
      });
      columns.push({
        title: this.$t("uc.finance.money.storagefee"),
        align: "center",
        render(h, params) {
          return h(
            "span",
            {
              attrs: {
                title: params.row.storageFee
              }
            },
            self.toFloor(params.row.storageFee || "0")
          );
        }
      });
      columns.push({
        title: this.$t("uc.finance.money.operate"),
        width: 300,
        align: "center",
        render: function(h, params) {
          var actions = [];
          // if (params.row.coin.enableBuy == 1) {
              // 买入
              actions.push(
                h(
                  "Button",
                  {
                    // 买入
                    props: {
                      type: "info",
                      size: "small"
                    },
                    on: {
                      click: function() {
                        localStorage.setItem("PARAMS", JSON.stringify({
                          pair: params.row.coin.symbol,
                          genre: (params.row.coin.genre).toString()
                        }));
                        self.$router.push("/exchange");
                        // self.$router.push(
                        //   "/exchange/exchange?symbol=" + params.row.coin.symbol
                        // );
                      }
                    },
                    style: {
                      marginRight: "8px"
                    }
                  },
                  self.$t("uc.finance.money.buy")
                )
              );
          // } else {
          //   actions.push(
          //     h(
          //       "Button",
          //       {
          //         props: {
          //           size: "small",
          //           disabled: true
          //         },
          //         on: {
          //           click: function() {
          //             self.modal = true;
          //           }
          //         },
          //         style: {
          //           marginRight: "8px"
          //         }
          //       },
          //       self.$t("uc.finance.money.buy")
          //     )
          //   );
          // }
          // if (params.row.coin.enableSell) {
            // 卖出
            actions.push(
              h(
                  "Button",
                  {
                    // 卖出
                    props: {
                      type: "info",
                      size: "small"
                    },
                    on: {
                      click: function() {
                        localStorage.setItem("PARAMS", JSON.stringify({
                          pair: params.row.coin.symbol,
                          genre: (params.row.coin.genre).toString()
                        }));
                        self.$router.push("/exchange");
                        // self.$router.push(
                        //   "/exchange/exchange?symbol=" + params.row.coin.symbol
                        // );
                      }
                    },
                    style: {
                      marginRight: "8px"
                    }
                  },
                  self.$t("uc.finance.money.sell")
                )
            );
          // } else {
          //   actions.push(
          //     h(
          //       "Button",
          //       {
          //         props: {
          //           size: "small",
          //           disabled: true
          //         },
          //         on: {
          //           click: function() {
          //           }
          //         },
          //         style: {
          //           marginRight: "8px"
          //         }
          //       },
          //       self.$t("uc.finance.money.sell")
          //     )
          //   );
          // }
          // if (params.row.coin.canWithdraw == 1) {
            // 提币;
            actions.push(
              h(
                "Button",
                {
                  props: {
                    type: "error",
                    size: "small"
                  },
                  on: {
                    click: function() {
                      self.rowVal = params.row;
                      self.modal = true;
                    }
                  },
                  style: {
                    marginRight: "8px"
                  }
                },
                self.$t("uc.finance.money.pickup")
              )
            );
          // }else{
          //   actions.push(
          //     h(
          //       "Button",
          //       {
          //         props: {
          //           size: "small",
          //           disabled: true
          //         },
          //         on: {
          //           click: function() {

          //           }
          //         },
          //         style: {
          //           marginRight: "8px"
          //         }
          //       },
          //       self.$t("uc.finance.money.pickup")
          //     )
          //   );
          // }
          return h("p", actions);
        }
      });
      return columns;
    }
  }
};
</script>
<style lang="scss">
.nav-right {
  .rightarea.bill_box {
    .shaow {
      padding: 5px;
    }
    .money_table {
      .search{
        width: 200px;
        margin-bottom: 10px;
      }
      .ivu-table-wrapper {
        .ivu-table-header{
          background: #27313e;
          th{
            color: #fff;
          }
        }
        .ivu-table-body {
          td {
            color: #fff;
            .ivu-table-cell {
              padding: 10px 10px;
              p .ivu-btn {
                background: transparent;
                height: 25px;
                padding: 0 0px;
                border-radius: 0;
                span {
                  display: inline-block;
                  line-height: 20px;
                  font-size: 12px;
                  padding: 0 15px;
                  letter-spacing: 1px;
                }
              }
              p .ivu-btn.ivu-btn-info {
                border: 1px solid #f0ac19;
                span {
                  color: #f0ac19;
                }
              }
              p .ivu-btn.ivu-btn-error {
                border: 1px solid #00b275;
                span {
                  color: #00b275;
                }
              }
              p .ivu-btn.ivu-btn-primary {
                border: 1px solid #f15057;
                span {
                  color: #f15057;
                }
              }
              p .ivu-btn.ivu-btn-default {
                border: 1px solid #2c384f;
                background: #222c3e;
                span {
                  color: #54637a;
                }
              }
            }
          }
        }
      }
    }
  }
}
</style>
<style scoped lang="scss">
.form-code {
  position: absolute;
  border: 1px solid #f0ac19;
  background: rgba(0,0,0,0);
  outline: none;
  right: 0;
  width: 30%;
  color: #f0ac19;
  cursor: pointer;
}
.nav-right {
  height: auto;
  overflow: hidden;
  padding: 0 0 0 15px;
  .rightarea.bill_box {
    padding-left: 15px;
    width: 100%;
    height: auto;
    overflow: hidden;
  }
}

.demo-spin-icon-load{
  animation: ani-demo-spin 1s linear infinite;
}
@media screen and (max-width:768px){
  .search{
    display: none;
  }
}

</style>
